<?php
require_once APPLICATION_PATH.'\misc\Paging.php';
require_once APPLICATION_PATH.'\misc\sessionController.php';
require_once APPLICATION_PATH.'\misc\additional.php';
class ShopController extends Zend_Controller_Action
{
    private $paramName = array('Super','admin');
    private $item_per_page;

    public function init()
    {
        $this->item_per_page = Paging::$number;
       $sessionController=new sessionController();

        if($sessionController->checkSessionAdmin($this->paramName)){
                $this->view->roleId = $sessionController->getSessionRoleId();
                $this->view->sessioncontroller = $sessionController;
              }else{
                  $this->_helper->redirector('login','admin');
              }
    }

    public function addLog($message){
        $sessionController = new sessionController();
        $actionLog = new Application_Model_DbTable_Actionlog();
        $actionLog->addActionLog($sessionController->getSessionLogId(),"[".$_SERVER['REMOTE_ADDR']."][".$sessionController->getSessionUsername()."] $message");
    }

    /**
     * Print Summary
     *
     *
     */
    public function indexAction() /* gunanya kalo ngetik shop tanpa action, langsung masuk index*/
    {
        $title = "Rangkuman";
        $this->view->title = $title;
        $this->view->headTitle($title);

        // Count shop in each category
        $cat_db = new Application_Model_DbTable_ShopType();
        $this->view->categories = $cat_db->countCategory();

        // Count shop in each status (accepted, pending, rejected)
        $shop_db = new Application_Model_DbTable_Shop();
        $this->view->accept = $shop_db->countStatus(Application_Model_DbTable_Shop::$SHOP_ACCEPT);
        $this->view->pending = $shop_db->countStatus(Application_Model_DbTable_Shop::$SHOP_PENDING);
        $this->view->reject = $shop_db->countStatus(Application_Model_DbTable_Shop::$SHOP_REJECT);

        // Count shop in each membership status
        $this->view->membership = $shop_db->countMembership();

        // Get high rate shops
        $this->view->rating5 = $shop_db->getHighRating(5);

        // Get high hits shops
        $this->view->hit5 = $shop_db->getHighHit(5);
    }

    public function addAction()
    {   $additional=new Additional();
        $form = new Application_Form_Shop();
        $form->submit->setLabel("Daftar");
        $this->view->form = $form;
        //$x = new Application_Model_DbTable_ShopKeyword();
        //echo count($x->assign());

        if ($this->getRequest()->isPost()) {
            $postData = $this->getRequest()->getPost();

            //Validate input data
            if ($form->isValid($postData)) {
                $shops = new Application_Model_DbTable_Shop();
                $shops->addShop($form->getValue("name"),
                        $form->getValue("owner"),
                        $form->getValue("address"),
                        $form->getValue("city"),
                        $form->getValue("phone"),
                        $form->getValue("email"),
                        $form->getValue("url"),
                        $form->getValue("description"),
                        $form->getValue("item_sold"),
                        $form->getValue("membership")
                );

                // get id of new shop
                $shop_id = $shops->getId($form->getValue("membership"),
                                $form->getValue("email"), $form->getValue("phone"));

                // Save picture
                $path = realpath('.')."\\images\\shops\\shop_".$shop_id."_main.png";
                $form->picture->addFilter("Rename",array('target'=>$path,'overwrite'=>true),$form->picture);
                $form->picture->receive();

                // Assign categories
                $categories = $form->getValue("category");
                $shoptype = new Application_Model_DbTable_ShopType();
                $shoptype->assign($shop_id, $categories);

                // Assign Keywords
                $keywords = explode(",", $form->getValue("keyword"));
                $shopkey = new Application_Model_DbTable_ShopKeyword();
                $shopkey->assign($shop_id, $keywords);
                /*
                // Send notification email to owner that the application will be evaluated
                $to = array($form->getValue("email")=>$form->getValue("owner"));
                $from = array("admin@bitz-plaza.com"=>"Bitz-Plaza Admin");
                $subject = "Permohonan pendaftaran toko Anda sudah kami terima";
                $body = "Terima kasih atas permohonan Anda untuk bergabung dengan kami\n".
                    "Kami akan memeriksa permohonan Anda dan Anda akan menerima email dari kami spabila permohonan Anda disetujui/detolak.\n\n".
                    "Berikut ini data dalam permohonan Anda:\n".
                    "Nama Toko: ".$form->getValue("name")."\n".
                    "Nama Anda: ".$form->getValue("owner")."\n".
                    "Alamat: ".$form->getValue("address")."\n".
                    "Kota: ".$form->getValue("city")."\n".
                    "No. Telp: ".$form->getValue("phone")."\n".
                    "Email: ".$form->getValue("email")."\n".
                    "Website: ".$form->getValue("url")."\n".
                    "Tentang toko: ".$form->getValue("description")."\n".
                    "Menjual: ".$form->getValue("item_sold");
                $additional->sendEmail($body,$to,$subject);
                 * 
                 */
           
                //Add log
                $this->addLog("Tambah Toko: ".$form->getValue("name"));

                $this->_helper->_flashMessenger->addMessage("Toko ".$form->getValue("name")." telah di daftarkan dan menunggu persetujuan");
                $this->_helper->redirector('list');
            }

            //Input is not valid
            else {
                $form->populate($postData);
            }
        }
    }

    public function editAction()
    {
        $title = "Edit Toko";
        $this->view->title = $title;
        $this->view->headTitle($title);

        $form = new Application_Form_Shop();
        $form->submit->setLabel("Simpan");
        $this->view->form = $form;

        $id = $this->getRequest()->getParam('id', 0);

        if ($this->getRequest()->isPost()) {
            $postData = $this->getRequest()->getPost();

            //Validate input data
            if ($form->isValid($postData)) {
                $shops = new Application_Model_DbTable_Shop();
                $shops->updateData($id,
                        $form->getValue("name"),
                        $form->getValue("owner"),
                        $form->getValue("address"),
                        $form->getValue("city"),
                        $form->getValue("province"),
                        $form->getValue("zip_code"),
                        $form->getValue("phone"),
                        $form->getValue("email"),
                        $form->getValue("url"),
                        $form->getValue("description"),
                        $form->getValue("item_sold"),
                        $form->getValue("membership")
                );
                
                // Assign categories, but unassign first
                $categories = $form->getValue("category");
                $shoptype = new Application_Model_DbTable_ShopType();
                $shoptype->unassign($id);
                $shoptype->assign($id, $categories);

                // Assign Keywords, but unassign first
                $keywords = explode(",", $form->getValue("keyword"));
                $shopkey = new Application_Model_DbTable_ShopKeyword();
                $shopkey->unassign($id);
                $shopkey->assign($id, $keywords);

                // Save picture
                $path = realpath('.')."\\images\\shops\\shop_".$id."_main.png";
                $form->picture->addFilter("Rename",array('target'=>$path,'overwrite'=>true),$form->picture);
                $form->picture->receive();
                
                //Add log
                $this->addLog("Ubah Toko: ".$form->getValue("name"));

                $this->_helper->_flashMessenger->addMessage("Toko ".$form->getValue("name")." telah berhasil di update");
                $this->_helper->redirector('list');
            } else {
                $form->populate($postData);
            }
        }
        else {
            if ($id > 0) {
                $shops = new Application_Model_DbTable_Shop();

                //get shop data
                $data = $shops->getShop($id);
                $data["membership"] = $data["membership_id"];
                $data["zip"] = $data["zip_code"];

                //get shop category
                $category = array();
                foreach($shops->getCategory($id) as $cat){
                    $category[] = $cat->category_id;
                }
                $data["category"] = $category;

                //get shop keyword
                $keyword = "";
                $count = 0;
                foreach($shops->getKeyword($id) as $key){
                    if($count > 0) $keyword .= ", ";
                    $keyword .= $key->name;
                    $count++;
                }
                $data["keyword"] = $keyword;

                $form->populate($data);
            }
        }
    }

    public function listAction()
    {
        $title = "Daftar Toko";
        $this->view->title = $title;
        $this->view->headTitle($title);
        $this->view->message = $this->_helper->_flashMessenger->getMessages();


        // If the request is POST, process POST data
        if ($this->getRequest()->isPost()) {

            if ($this->getRequest()->getParam("delete")) {
                $id = $this->getRequest()->getParam("shopId");
                $name = $this->getRequest()->getParam("shopName");

                $db = new Application_Model_DbTable_Shop();
                $shop= $db->getShop($id);
                $db->deleteShop($id);

                //Add log
                $this->addLog("Hapus Toko Aktif: $name");

                $this->_helper->_flashMessenger->addMessage("Toko $name telah berhasil di hapus");
                $this->_helper->redirector('list');
                
            }   
        }
    }

    public function pendingAction()
    {
        $title = "Toko Belum Disetujui";
        $this->view->title = $title;
        $this->view->headTitle($title);

        // If the request is POST, process POST data
        if ($this->getRequest()->isPost()) {
            $id = $this->getRequest()->getParam("shopId");
            $name = $this->getRequest()->getParam("shopName");
            $db = new Application_Model_DbTable_Shop();

            //Log the changing
            $sessionController = new sessionController();
            $actionLog = new Application_Model_DbTable_Actionlog();

            if ($this->getRequest()->getParam("pending")) {
            $this->_helper->_flashMessenger->addMessage("Toko $name telah di tolak untuk pengamatan lebih jauh");
                $reason = $this->getRequest()->getParam("reason");
                $db->updateStatus($id, 2, $reason);

                //Add log
                $this->addLog("Tolak Toko yang Belum Disetujui: $name ");
            } else if ($this->getRequest()->getParam("reject")) {
                $this->_helper->_flashMessenger->addMessage("Toko $name telah di hapus dari Bitzplaza");
                $db->deleteShop($id);

                //Add log
                $this->addLog("Hapus Toko yang Belum Disetujui: $name");
            } else if ($this->getRequest()->getParam("accept")) {
                $db->updateStatus($id, 1);
                $this->_helper->_flashMessenger->addMessage("Toko $name telah di setujui");

                //Add log
                $this->addLog("Setujui Toko yang Belum Disetujui: $name");
            }
            $this->_helper->redirector('pending');
        }

        // parameter for database query
        $page = $this->getRequest()->getParam("page",1);
        $this->view->page = $page;

        // Load pending approved shop from database
        $this->view->message = $this->_helper->_flashMessenger->getMessages();
        $shop_db = new Application_Model_DbTable_Shop();
        $shops = $shop_db->getAll($this->item_per_page,$page,"status = 0");
        $this->view->shops = $shops;

        // Load categories of each shop
        $shops_type = array();
        foreach ($shops as $shop) {
            $cats = $shop_db->getCategory($shop["shop_id"]);

            // List categories
            $category = array();
            foreach ($cats as $cat) {
                $category[] = $cat->cat_name;
            }

            // Save category into particular shop
            $shops_type[$shop["shop_id"]] = $category;
        }
        $this->view->shops_type = $shops_type;

        // Load keywords of each shop
        $shops_key = array();
        foreach ($shops as $shop) {
            $keys = $shop_db->getKeyword($shop["shop_id"]);

            // List keywords
            $keyword = array();
            foreach ($keys as $key) {
                $keyword[] = $key->name;
            }

            // Save keywords into particular shop
            $shops_key[$shop["shop_id"]] = $keyword;
        }
        $this->view->shops_key = $shops_key;

        //table's navigator
        $paging = new Paging();
        $tpage = $paging->totalPages($shop_db->countRows('status = 0'));
        if($tpage>1){
            $this->view->back = $paging->back("shop","pending",$page,null,null);
            $this->view->current = $paging->current("shop","pending",$tpage,$page,null,null)."/ $tpage";
            $this->view->next = $paging->next("shop","pending",$tpage,$page,null,null);
        }
    }

    public function detailsAction()
    {
        $id = $this->_getParam('id', 0);
        if ($id > 0) {
            $shop_db = new Application_Model_DbTable_Shop();
            $shop = $shop_db->getShop($id);
            $this->view->shop = $shop;

            // Get categories
            $this->view->categories = $shop_db->getCategory($id);

            // Get keywords
            $this->view->keywords = $shop_db->getKeyword($id);

            $title = $shop["name"];
            $this->view->title = $title;
            $this->view->headTitle($title);
        } else {
            $this->_helper->redirector('list');
        }
    }

    public function rejectedAction()
    {
        // If the request is POST, process POST data
        if ($this->getRequest()->isPost()) {
            $id = $this->getRequest()->getParam("shopId");
            $name = $this->getRequest()->getParam("shopName");
            $db = new Application_Model_DbTable_Shop();

            //Log the changing
            $sessionController = new sessionController();
            $actionLog = new Application_Model_DbTable_Actionlog();

            if ($this->getRequest()->getParam("delete")) {
                $this->_helper->_flashMessenger->addMessage("Toko $name tidak disetujui dan telah dihapus");
                $db->deleteShop($id);

                //Add log
                $this->addLog("Hapus Toko yang Ditolak: $name");
            }

            else if($this->getRequest()->getParam("accept")) {
                $this->_helper->_flashMessenger->addMessage("Toko $name telah diseleksi dan disetujui");
                $db->updateStatus($id, 1);

                //Add log
                $this->addLog("Setujui Toko yang Ditolak: $name");
            }

            $this->_helper->redirector('rejected');
        }

        // action body
        $title = "Toko Ditolak";
        $this->view->title = $title;
        $this->view->headTitle($title);

        $page = $this->getRequest()->getParam("page",1);
        $this->view->page = $page;

        // Load rejected shop from database
        $this->view->message = $this->_helper->_flashMessenger->getMessages();
        $shop_db = new Application_Model_DbTable_Shop();
        $shops = $shop_db->getAll($this->item_per_page,$page,"status = 2");
        $this->view->shops = $shops;

        // Load categories of each shop
        $shops_type = array();
        foreach ($shops as $shop) {
            $cats = $shop_db->getCategory($shop["shop_id"]);

            // List categories
            $category = array();
            foreach ($cats as $cat) {
                $category[] = $cat->cat_name;
            }

            // Save category into particular shop
            $shops_type[$shop["shop_id"]] = $category;
        }
        $this->view->shops_type = $shops_type;

        // Load keywords of each shop
        $shops_key = array();
        foreach ($shops as $shop) {
            $keys = $shop_db->getKeyword($shop["shop_id"]);

            // List keywords
            $keyword = array();
            foreach ($keys as $key) {
                $keyword[] = $key->name;
            }

            // Save keywords into particular shop
            $shops_key[$shop["shop_id"]] = $keyword;
        }
        $this->view->shops_key = $shops_key;
        
        //table's navigator
        $paging = new Paging();
        $tpage = $paging->totalPages($shop_db->countRows('status = 2'));
        if($tpage>1){
            $this->view->back = $paging->back("shop","rejected",$page,null,null);
            $this->view->current = $paging->current("shop","rejected",$tpage,$page,null,null)."/ $tpage";
            $this->view->next = $paging->next("shop","rejected",$tpage,$page,null,null);
        }
    }

    public function categoryAction()
    {
        $title = "Kategori";
        $this->view->title = $title;
        $this->view->headTitle($title);

        $form = new Application_Form_Shop();
        $category = new Application_Model_DbTable_Category();
        $formDisplay = new Application_Form_Display();
        $this->view->message = $this->_helper->_flashMessenger->getMessages();
        $form->name->setLabel("Nama Kategori");
        $form->description->setLabel("Keterangan");
        $formDisplay->addElements(array($form->name, $form->description));
        //display formnya
        $this->view->form = $formDisplay;

        $getnamecategory = $category->getNameCategory($this->getRequest()->getParam("categoryID"));
       

        
        //bu'on udah di tekan
        if ($this->getRequest()->isPost()) {
            $postData = $this->getRequest()->getPost();

          //hapus data
             if ($this->getRequest()->getParam("delete")) {
                    $db = new Application_Model_DbTable_Category();
                    $this->_helper->_flashMessenger->addMessage("Kategori ".$db->getNameCategory($this->getRequest()->getParam("categoryID"))." telah dihapus");
                    $db->deleteCategory($this->getRequest()->getParam("categoryID"));

                    //Add log
                    $sessionController = new sessionController();
                    $actionLog = new Application_Model_DbTable_Actionlog();
                    $this->addLog("Hapus Kategori: ".$this->getRequest()->getParam("categoryName"));

                    $this->_helper->redirector("category");
            }
            else{
                //Validate input data
                if ($formDisplay->isValid($postData)) {
                    //masukin data2 kedalam table
                $this->_helper->_flashMessenger->addMessage("Kategori ".$form->getValue("name")." telah ditambahkan");
                    $category->addCategory($form->getValue("name"),
                $formDisplay->getValue("description")
                    );

                    //Add log
                    $this->addlog("Tambah Kategori: ".$form->getValue("name"));

                    $this->_helper->redirector('category');
              
                }


                //Input is not valid
                else {
                    $formDisplay->populate($postData);
                }
            }
        }
        
        $this->view->categories = $category->fetchAll();


    }

    public function searchAction()
    {
        $this->_helper->layout()->disableLayout();

        // parameter for database query
        $name = $this->getRequest()->getParam("name");
        $order = $this->getRequest()->getParam("order","name");
        $method = $this->getRequest()->getParam("method","asc");
        $page = $this->getRequest()->getParam("page",1);
        $this->view->page = $page;
        $this->view->order = $order;
        $this->view->method = $method;

        //get shops
        $shop_db = new Application_Model_DbTable_Shop();
        if($name!=null || strlen($name)!=0){
            $shops = $shop_db->getAll($this->item_per_page,$page,"status = 1 AND name like '%$name%'",$order,$method);
        }else{
            $shops = $shop_db->getAll($this->item_per_page,$page,"status = 1",$order,$method);
        }
        $this->view->shops = $shops;

        // Load categories of each shop
        $shops_type = array();
        foreach ($shops as $shop) {
            $cats = $shop_db->getCategory($shop["shop_id"]);

            // List categories
            $category = array();
            foreach ($cats as $cat) {
                $category[] = $cat->cat_name;
            }

            // Save category into particular shop
            $shops_type[$shop["shop_id"]] = $category;
        }
        $this->view->shops_type = $shops_type;

        // Load keywords of each shop
        $shops_key = array();
        foreach ($shops as $shop) {
            $keys = $shop_db->getKeyword($shop["shop_id"]);

            // List keywords
            $keyword = array();
            foreach ($keys as $key) {
                $keyword[] = $key->name;
            }

            // Save keywords into particular shop
            $shops_key[$shop["shop_id"]] = $keyword;
        }
        $this->view->shops_key = $shops_key;

        //table's navigator
        $paging = new Paging();
        if($name!=null || strlen($name)!=0){
            $tpage = $paging->totalPages($shop_db->countRows("status = 1 AND name like '%$name%'"));
        }else{
            $tpage = $paging->totalPages($shop_db->countRows("status = 1"));
        }
        if($tpage>1){
            $this->view->back = $paging->back("shop","search",$page,$order,$method,null);
            $this->view->current = $paging->current("shop","search",$tpage,$page,$order,$method,null)."/ $tpage";
            $this->view->next = $paging->next("shop","search",$tpage,$page,$order,$method,null);
        }
    }

    public function editcategoryAction()
    {
       $title = "Edit Kategori";
        $this->view->title = $title;
        $this->view->headTitle($title);
        $form = new Application_Form_Category();
        $form->submit->setLabel("Simpan");
        $this->view->form = $form;

        $id = $this->getRequest()->getParam('id', 0);

        if ($this->getRequest()->isPost()) {
            $postData = $this->getRequest()->getPost();

            //Validate input data
            if ($form->isValid($postData)) {
                $categories = new Application_Model_DbTable_Category();
                $categories->updateCategory($id,
                        $form->getValue("name"),
                        $form->getValue("details")
                       
                );

                $this->_helper->_flashMessenger->addMessage("Kategori ".$form->getValue("name")." telah berhasil di update");
                $this->_helper->redirector('category');
            } else {
                $form->populate($postData);
            }
        }
        else {
            if ($id > 0) {
                $categories = new Application_Model_DbTable_Category();

                //get category data
                $categorydata = $categories->getCategory($id);//getShop($id);
                $count = 0;
                $form->populate($categorydata);
            }
        }
    }

    

    
}



